import pkg from "../../package.json";
import { useTextStyles } from "./Stylex";
import { randsl, tr } from "./Translator";
import { FlightTakeoff, GetApp, History, PermContactCalendar, RocketLaunch, Settings } from "@mui/icons-material";
import React, { useEffect, useRef, useState } from "react";
import { makeStyles } from "@mui/styles";
import { AlicornTheme, useInputStyles } from "./Stylex";
import { ipcRenderer, webFrame } from "electron";
import os from "os";
import {
	Box,
	Button,
	Container,
	FormControlLabel,
	Grid,
	Radio,
	RadioGroup,
	Slider,
	Switch,
	Tab,
	Tabs,
	TextField,
	ThemeProvider,
	Typography,
} from "@mui/material";
import { ALICORN_DEFAULT_THEME_DARK, ALICORN_DEFAULT_THEME_LIGHT, isBgDark } from "./Renderer";
import {
	get,
	getBoolean,
	getNumber,
	getString,
	parseNum,
	saveConfig,
	set,
} from "../modules/config/ConfigSupport";
import { remoteSelectDir } from "./ContainerManager";
import { getActualDataPath } from "../modules/config/DataSupport";
import { copy } from "fs-extra";
import { buildMap, parseMap } from "../modules/commons/MapUtil";

let STATISTICS_MAP: Map<string, number> = new Map();
const ALL_STATS = ["Click", "Launch", "Crash"];
const modeList = ["Copyright", "Privacy", "Credit"];

enum ConfigType {
		BOOL,
		NUM,
		STR,
		DIR,
		RADIO,
		FILE,
		SLIDE,
	}


	export function About(): JSX.Element {
		const [tabValue, setTabValue] = useState(0);
		const classes = useTextStyles();

		const [ecVersion, setEcVersion] = useState(
			tr("VersionView.Electron.Fetching")
		  );
		  const [displayMode, setDisplayMode] = useState(0);
		  useEffect(() => {
			void (async () => {
			  setEcVersion(await ipcRenderer.invoke("getElectronVersion"));
			})();
		  }, []);

		return (

			<Container>
				<ThemeProvider
					theme={
						isBgDark() ? ALICORN_DEFAULT_THEME_DARK : ALICORN_DEFAULT_THEME_LIGHT
					}
				>
					{/* Tabs */}
					<Tabs
						variant={"fullWidth"}
						value={tabValue}
						onChange={(_e, v) => {
							setTabValue(v);
						}}
					>
						<Tab
							label={
								<Typography color={"primary"}>
									{tr("About.Page.Thinking")}
								</Typography>
							}
						/>
						<Tab
							label={
								<Typography color={"primary"}>
									{tr("About.Page.Info")}
								</Typography>
							}
						/>
						<Tab
							label={
								<Typography color={"primary"}>
									{tr("About.Page.Ending")}
								</Typography>
							}
						/>
					</Tabs>

					<TabPanel index={2} value={tabValue}>
						<>
							<Typography className={classes.firstText} color={"primary"}>
								{tr("EOE.Thanks")}
							</Typography>
							<Typography className={classes.secondText} gutterBottom>
								{tr("EOE.ThanksDesc")}
							</Typography>
							<Typography className={classes.thirdTextRaw} color={"primary"}>
								{tr("EOE.Packages")}
							</Typography>
							<Typography className={classes.secondText} gutterBottom>
								{Object.keys(pkg.dependencies)
									.concat(Object.keys(pkg.devDependencies))
									.join(" ")}
							</Typography>
							<Typography className={classes.thirdTextRaw} color={"primary"}>
								{tr("EOE.And")}
							</Typography>
							<Typography className={classes.secondText} gutterBottom>
								{tr("EOE.Orgs")}
							</Typography>
							<br />
							<Typography className={classes.firstText} color={"primary"}>
								{tr("EOE.StoryTitle")}
							</Typography>
							<Typography className={classes.secondText} gutterBottom>
								{tr("EOE.Story")}
							</Typography>
							<br />
							<Typography className={classes.firstText} color={"primary"}>
								{tr("EOE.EndPoem")}
							</Typography>
							<Typography className={classes.secondText} gutterBottom>
								{tr("EOE.EndPoemContent")}
							</Typography>
						</>
					</TabPanel>

					<TabPanel index={0} value={tabValue}>
						{/* 看上去是某些变量出了问题w */}
						{ALL_STATS.map((v) => {
							const s = getStatistics(v);
							return (
								<Box key={v}>
									<Box sx={{ display: "flex" }}>
										<Typography className={classes.mediumText}>
											{
												tr(
													"Statistics." + v,
													`Value=${s}`
												) /* randsl to apply condition */
											}
										</Typography>
										<Typography
											className={classes.secondText}
											sx={{ marginLeft: "auto" }}
										>
											{randsl("Statistics." + v + ".As", `Value=${s}`)}
										</Typography>
									</Box>
									<br />
								</Box>
							);
						})}
					</TabPanel>

					<TabPanel index={1} value={tabValue}>
						<Box className={classes.root}>
							<Typography className={classes.firstText} gutterBottom>
								{tr(
									"VersionView.Name",
									`AppVersion=${pkg.appVersion}`,
									`UpdatorVersion=${pkg.updatorVersion}`
								)}
							</Typography>
							<Typography className={classes.secondText} color={"secondary"}>
								{tr(
									"VersionView.EcVersion",
									`Build=${pkg.devDependencies.electron.slice(1)}`,
									`Current=${ecVersion}`
								)}
							</Typography>
							<Typography className={classes.secondText} color={"secondary"} gutterBottom>
								{tr(
									"VersionView.Electron." +
									cmpVersion(ecVersion, pkg.devDependencies.electron.slice(1))
								)}
							</Typography>
							<Typography className={classes.secondText} color={"secondary"} gutterBottom>
								{tr("VersionView.Description")}
							</Typography>
							<br />
							<Typography className={classes.secondText} color={"secondary"} gutterBottom>
								{tr("VersionView.FreeSoftwareClaim")}
							</Typography>
							<Box
								onClick={() => {
									setDisplayMode((v) => {
										let r = v + 1;
										if (r >= modeList.length) {
											r = 0;
										}
										return r;
									});
								}}
							>
								<Typography className={classes.secondText} color={"secondary"} gutterBottom>
									{tr("VersionView." + modeList[displayMode])}
								</Typography>
								<Typography className={classes.secondText} color={"secondary"} gutterBottom>
									{tr("VersionView.ClickToSeeNext")}
								</Typography>
							</Box>
							<Typography
								className={classes.firstText}
								color={"primary"}
								sx={{
									float: "right",
									marginRight: "2%",
								}}
							>
								{tr("VersionView.SuperCowPower")}
							</Typography>
						</Box>
					</TabPanel>


				</ThemeProvider>

			</Container>

		)
	}

	//下面的是显示(?的东西，虽然不知道它是什么原理，但是它有效果w
	function InputItem(props: {
		type: ConfigType;
		bindConfig: string;
		icon?: React.ReactNode;
		choices?: string[];
		onlyOn?: NodeJS.Platform;
		notOn?: NodeJS.Platform;
		onChange?: () => unknown;
		experimental?: boolean;
		reload?: boolean;
		save?: boolean; // Path selector
		sliderMax?: number;
		sliderMin?: number;
		sliderStep?: number;
	}): JSX.Element {
		const originVal = useRef(get(props.bindConfig, undefined));
		const callChange = () => {
			if (
				get(props.bindConfig, undefined) !== originVal.current &&
				props.reload
			) {
				sessionStorage.setItem("Options.Reload", "1");
			}
			if (props.onChange) {
				props.onChange();
			}
		};
		const [refreshBit, forceRefresh] = useState<boolean>(true);
		const classex = useInputStyles();
		const [cSelect, setSelect] = useState<string>(
			getString(props.bindConfig, (props.choices || [""])[0] || "")
		);
		useEffect(() => {
			saveConfig()
				.then(() => { })
				.catch(() => { });
		});
		let disabled = false;
		if (props.onlyOn) {
			if (os.platform() !== props.onlyOn) {
				disabled = true;
			}
		}
		if (props.notOn) {
			if (os.platform() === props.notOn) {
				disabled = true;
			}
		}
		const classes = makeStyles((theme: AlicornTheme) => ({
			desc: {
				color: theme.palette.secondary.main,
			},
			switch: {
				color: theme.palette.primary.main,
				marginLeft: theme.spacing(0.5),
			},

			textField: {
				borderColor: theme.palette.primary.main,
				color: theme.palette.primary.main,
			},
			title: {
				color: theme.palette.primary.main,
				fontSize: "large",
			},
		}))();
		if (props.experimental) {
			if (!getBoolean("dev.experimental")) {
				return <></>;
			}
		}
		return (
			<Container>
				<Grid container direction="row" alignItems="center">
					<Grid item sx={{ color: "primary.main" }}>
						{props.icon || <Settings />}
					</Grid>
					<Grid item>
						<Typography
							color={"primary"}
							variant={"h6"}
							sx={{ marginLeft: "0.25rem" }}
							className={classes.title}
						>
							{tr(`Options.${props.bindConfig}.title`)}
						</Typography>
					</Grid>
				</Grid>
				<Typography color={"secondary"} className={classes.desc} gutterBottom>
					{disabled
						? tr("Options.NotOn")
						: tr(`Options.${props.bindConfig}.desc`)}
				</Typography>
				{(() => {
					switch (props.type) {
						case ConfigType.BOOL:
							return (
								<FormControlLabel
									label={
										<Typography color={"primary"}>
											{getBoolean(props.bindConfig)
												? tr("Options.Enabled")
												: tr("Options.Disabled")}
										</Typography>
									}
									control={
										<Switch
											size={"small"}
											disabled={disabled}
											checked={getBoolean(props.bindConfig)}
											className={classes.switch}
											onChange={(e) => {
												markEdited(props.bindConfig);
												set(props.bindConfig, e.target.checked);
												forceRefresh(!refreshBit);
												callChange();
											}}
											name={
												getBoolean(props.bindConfig)
													? tr("Options.Enabled")
													: tr("Options.Disabled")
											}
										/>
									}
								/>
							);
						case ConfigType.NUM:
							return (
								<TextField
									disabled={disabled}
									spellCheck={false}
									fullWidth
									variant={"outlined"}
									type={"number"}
									color={"primary"}
									value={getNumber(props.bindConfig)}
									onChange={(e) => {
										markEdited(props.bindConfig);
										set(props.bindConfig, parseNum(e.target.value, 0));
										forceRefresh(!refreshBit);
										callChange();
									}}
								/>
							);

						case ConfigType.DIR:
						case ConfigType.FILE:
							return (
								<>
									<TextField
										disabled={disabled}
										fullWidth
										variant={"outlined"}
										spellCheck={false}
										color={"primary"}
										value={getString(props.bindConfig)}
										onChange={(e) => {
											markEdited(props.bindConfig);
											set(props.bindConfig, String(e.target.value || ""));
											forceRefresh(!refreshBit);
											callChange();
										}}
									/>
									<Button
										className={classex.inputDark}
										type={"button"}
										variant={"contained"}
										sx={{
											marginTop: "0.25rem",
										}}
										onClick={async () => {
											let d =
												props.type === ConfigType.DIR
													? await remoteSelectDir()
													: await remoteSelectFile();
											if (d.trim().length === 0) {
												return;
											}

											try {
												const target = getActualDataPath(
													props.bindConfig.replaceAll("?", "") + ".ald"
												);
												await copy(d, target);
												d = target;
											} catch { }
											set(props.bindConfig, d);
											markEdited(props.bindConfig);
											forceRefresh(!refreshBit);
											callChange();
										}}
									>
										{tr("Options.Select")}
									</Button>
								</>
							);
						case ConfigType.STR:
						default:
							return (
								<TextField
									disabled={disabled}
									fullWidth
									variant={"outlined"}
									spellCheck={false}
									color={"primary"}
									value={getString(props.bindConfig)}
									onChange={(e) => {
										markEdited(props.bindConfig);
										set(props.bindConfig, String(e.target.value || ""));
										forceRefresh(!refreshBit);
										callChange();
									}}
								/>
							);
					}
				})()}
				<br />
				<br />
			</Container>
		);
	}

	async function remoteSelectFile(): Promise<string> {
		return String((await ipcRenderer.invoke("selectFile")) || "");
	}

	function TabPanel(props: {
		children?: React.ReactNode;
		index: string | number;
		value: string | number;
	}): JSX.Element {
		const { children, value, index } = props;
		return (
			<Box hidden={value !== index}>
				{value === index ? <Box p={3}>{children}</Box> : ""}
			</Box>
		);
	}

	function markEdited(bindConfig: string) {
		throw new Error("Function not implemented.");
	}
	// 下面的是统计信息的东西
	export function initStatistics(): void {
		loadStatistics();
		window.addEventListener("click", () => {
			addStatistics("Click");
		});
		window.addEventListener("keydown", () => {
			addStatistics("Keyboard");
		});
	}

	export function addStatistics(i: string, amount = 1): void {
		STATISTICS_MAP.set(i, (STATISTICS_MAP.get(i) || 0) + amount);
	}

	function getStatistics(i: string): number {
		return STATISTICS_MAP.get(i) || 0;
	}

	export function saveStatistics(): void {
		localStorage.setItem("Statistics", buildMap(STATISTICS_MAP));
	}

	function loadStatistics(): void {
		STATISTICS_MAP = parseMap(localStorage.getItem("Statistics") || "");
	}

	//这里是'关于'项的东西
	function cmpVersion(
		current: string,
		build: string
	): "Perfect" | "OK" | "Attention" {
		if (current === build) {
			return "Perfect";
		}
		if (current.split(".")[0] === build.split(".")[0]) {
			return "OK";
		}
		return "Attention";
	}